/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

// 2021.4.19
// class Solution {
// public:
//     ListNode* reverseList(ListNode* head) {
//         if(!head)return head;
//         if(!head->next)return head;
//         ListNode *first = head->next, *second = head, *temp = nullptr;
//         while(first){
//             second->next = temp;
//             temp = second;
//             second = first;
//             first = first->next;
//         }
//         second->next = temp;
//         return second;
//     }
// };


class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head || !head->next)return head;
        ListNode *p = head, *q = head->next, *r = head->next->next;
        while(r){
            q->next = p;
            p = q;
            q = r;
            r = r->next;
        }
        q->next = p;
        head->next = nullptr;
        return q;
    }
};

//2021.4.19 
/**
 * 2021.9.27 update
 * 需要三个指针，前两个指针负责翻转，第三个指针为前两个指针找方向
 */
